﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Collection.Generic;
using NHibernate;
using System.Net.Mail;

namespace Mailer.Model.Types
{
	public class Application
	{
		public virtual Guid ID { get; set; }
		public virtual string PublicID { get; set; }
		public virtual string Secret { get; set; }
		public virtual string Name { get; set; }
		public virtual string ShortName { get; set; }
		public virtual int State { get; set; }

		public virtual IList<List> Lists { get; set; }
		public virtual IList<Mail> Mails { get; set; }
		public virtual IList<Recipient> Recipients { get; set; }
		public virtual IList<ApplicationProperty> Properties { get; set; }

		public Application()
		{
			Lists = new List<List>();
			Mails = new List<Mail>();
			Recipients = new List<Recipient>();
			Properties = new List<ApplicationProperty>();
		}

		public virtual string GetPropertyValue(string propertyname)
		{
			return GetPropertyValue(propertyname, "");
		}

		public virtual string GetPropertyValue(string propertyname, string defaultvalue)
		{
			foreach (ApplicationProperty ap in Properties)
			{
				if (ap.Name == propertyname)
					return ap.Value;
			}

			return defaultvalue;
		}

		public virtual void SetPropertyValue(ISession session, string propertyname, string propertyvalue)
		{
			//	ISession sess = SessionUtilities.GetSession();
			//	if (sess != null)
			//	{
			bool found = false;
			foreach (ApplicationProperty ap in Properties)
			{
				if (ap.Name == propertyname)
				{
					ap.Value = propertyvalue;
					session.Save(ap);
					found = true;
				}
			}

			if (!found)
			{
				ApplicationProperty newap = new ApplicationProperty();
				newap.ApplicationID = ID;
				newap.Name = propertyname;
				newap.Value = propertyvalue;
				session.Save(newap);
				Properties.Add(newap);
			}

			//	}
		}



		public virtual MailAddress GetSenderAddress()
		{
			return new MailAddress( GetPropertyValue( "senderemail" ), GetPropertyValue( "sendername" ) );
		}

		public virtual MailAddress GetToAddress()
		{
			return new MailAddress(GetPropertyValue("recipientemail"), GetPropertyValue("recipientname"));
		}

		public virtual MailAddress GetReplyToAddress()
		{
			return new MailAddress( GetPropertyValue( "replytoemail" ));
		}
	}
}
